#!/bin/tcsh -ef
#############################################################################
#                                                                           #
# Title: Import Images & Movies                                             #
#                                                                           #
# (C) 2dx.org, GNU Plublic License.                                         #
#                                                                           #
# Created..........: 10/28/2014                                             #
# Last Modification: 08/21/2016                                             #
# Author...........: 2dx.org                                                #
#                                                                           #
#############################################################################
#
# SORTORDER: 5 
#
# MANUAL: This script allows to import dose-fractionated movies and their drift-corrected average images.
#
# DISPLAY: import_dir
# DISPLAY: import_imagenumber
# DISPLAY: import_target_dir
# DISPLAY: import_type
# DISPLAY: import_DC_stacks_do
# DISPLAY: import_RAW_stacks_do
# DISPLAY: import_DC_averages_folder
# DISPLAY: import_DC_stacks_folder
# DISPLAY: import_RAW_stacks_folder
#
#$end_local_vars
#
# This defines some variables that we might need:
set proc_2dx = ""
set bin_2dx = ""
#
set import_dir = ""
set import_imagenumber = ""
set import_target_dir = ""
set import_type = ""
set import_DC_stacks_do = ""
set import_RAW_stacks_do = ""
set import_DC_averages_folder = ""
set import_DC_stacks_folder = ""
set import_RAW_stacks_folder = ""
#
#$end_vars
#
# This sets the scriptname variable:
set scriptname = 2dx_moviemode_import
#
# This removes the old logfile, so that a new fresh one can be created:
\rm -f LOGS/${scriptname}.results
#
# This initializes the ccp4 environment, and other variables.
set ccp4_setup = 'y'
source ${proc_2dx}/initialize
#
# This advances the progress bar to the 1% position:
echo "<<@progress: 1>>"
#
# This creates all needed subdirectories in the current merge directory, in case they are missing:
source ${proc_2dx}/2dx_makedirs 
#
# This memorizes the current merge directory under the variable "olddir":
set olddir = $PWD
#
if ( ${import_type} == 0 ) then
  set file_ending = "mrc"
else
  set file_ending = "tiff"
endif
#
echo "<<@progress: 10>>"
#
set movie_average = ${import_dir}/${import_DC_averages_folder}
set movie_stack   = ${import_dir}/${import_DC_stacks_folder}
set movie_RAW     = ${import_dir}/${import_RAW_stacks_folder}
#
if ( ! -d ${movie_average} ) then
  ${proc_2dx}/protest "ERRROR: directory ${movie_average} not found."
endif
#
if ( ${import_DC_stacks_do} == "y" ) then
  if ( ! -d ${movie_stack} ) then
    ${proc_2dx}/protest "ERRROR: directory ${movie_stack} not found."
  endif
endif
#
if ( ${import_RAW_stacks_do} == "y" ) then
  if ( ! -d ${movie_RAW} ) then
    ${proc_2dx}/protest "ERRROR: directory ${movie_RAW} not found."
  endif
endif
#
cd ${movie_average}
ls -1 *.${file_ending} > ${olddir}/tmp.tmp
cd ${olddir}
set imagenum = `cat tmp.tmp | wc -l`
echo ":: Importing ${imagenum} images"
#
set import_target_dirname = `echo ${import_target_dir} | sed -e 's/\./_/g' -e 's/\,/_/g' -e 's/ /_/g' -e's/:/_/g' -e's/#/_/g' -e 's/+/_/g'`
cd ..
if ( ! -d ${import_target_dirname} ) then
  \mkdir ${import_target_dirname}
  ${proc_2dx}/linblock "Creating ${import_target_dirname}"
  cd ${import_target_dirname}
  \ln -s ../2dx_master.cfg .
endif
cd ${olddir}
#
set irun = 1
while ( ${irun} <= ${imagenum} )
  set prog_num = `echo ${irun} ${imagenum} | awk '{ s = 10 + int( 80 * $1 / $2 ) } END { print s }'` 
  echo "<<@progress: ${prog_num}>>"
  #
  set importimage = `sed -n "${irun}p" tmp.tmp`
  if ( ${import_type} == 0 ) then
    set importimage_pattern = `echo ${importimage} | sed -e's/_aligned\.mrc//g'  -e's/\.mrc//g'  -e 's/\./-/g' -e 's/\,/-/g' -e 's/ /-/g' -e's/:/-/g' -e's/#/-/g'`
  else
    set importimage_pattern = `echo ${importimage} | sed -e's/_aligned\.tiff//g' -e's/\.tiff//g' -e 's/\./-/g' -e 's/\,/-/g' -e 's/ /-/g' -e's/:/-/g' -e's/#/-/g'`
  endif
  #
  if ( -e ${movie_average}/${importimage} ) then
    set newval = `echo ${import_imagenumber} | awk '{ s = $1 * 100 } END { print s }'`
    set testval = `echo ${newval} | wc -c`
    set newimagenumber = `echo 0000000000 | cut -c${testval}-`${newval}
    echo ":"
    echo ":: ${irun}: Creating ${import_target_dirname}/${importimage_pattern} for image number ${newimagenumber}"
    echo ":"
    echo ":         Importing drift-corrected average image "
    echo ":              ${movie_average}/${importimage}"
    set stack_found = "n"
    if ( ${import_DC_stacks_do} == "y" ) then
      if ( -e ${movie_stack}/${importimage} ) then
        echo ": and drift-corrected stack"
        echo ":      ${movie_stack}/${importimage}"
        set DC_stack_found = "y"
      else
        echo "::        WARNING: ${movie_stack}/${importimage} not found."
        set DC_stack_found = "n"
      endif
    else
      set DC_stack_found = "n"
    endif
    if ( ${import_RAW_stacks_do} == "y" ) then
      if ( -e ${movie_RAW}/${importimage} ) then
        echo ": and raw stack"
        echo ":      ${movie_RAW}/${importimage}"
        set RAW_stack_found = "y"
      else
        echo "::        WARNING: ${movie_RAW}/${importimage} not found."
        set RAW_stack_found = "n"
      endif
    else
      set RAW_stack_found = "n"
    endif
    cd ${olddir}
    cd ..
    cd ${import_target_dirname}
    if ( -d ${importimage_pattern} ) then
      echo "::        WARNING: ${importimage_pattern} already existing. Removing."
      \rm -rf ${importimage_pattern}
    endif
    mkdir ${importimage_pattern}
    cd ${importimage_pattern}
    cp ${movie_average}/${importimage} ${importimage_pattern}_${newimagenumber}_raw.${file_ending}
    if ( ${import_DC_stacks_do} == "y" && ${DC_stack_found} == "y") then
      cp ${movie_stack}/${importimage} ${importimage_pattern}_${newimagenumber}_stack.${file_ending}
    endif
    if ( ${import_RAW_stacks_do} == "y" && ${RAW_stack_found} == "y") then
      cp ${movie_RAW}/${importimage} ${importimage_pattern}_${newimagenumber}_stack_raw.${file_ending}
    endif
    #
    cp ${olddir}/2dx_merge.cfg 2dx_image.cfg
    #
    # This tells the GUI that the parameters are now to be added in the current image directory
    echo "<IMAGEDIR="\"${PWD}\"">" >> ${olddir}/LOGS/${scriptname}.results
    #
    echo "set imagename = ${importimage_pattern}_${newimagenumber}" >> ${olddir}/LOGS/${scriptname}.results
    echo "set nonmaskimagename = ${importimage_pattern}_${newimagenumber}" >> ${olddir}/LOGS/${scriptname}.results
    if ( ${import_DC_stacks_do} == "y" && ${DC_stack_found} == "y") then
      echo "set movie_stackname = ${importimage_pattern}_${newimagenumber}_stack.${file_ending}" >> ${olddir}/LOGS/${scriptname}.results
    endif
    if ( ${import_RAW_stacks_do} == "y" && ${RAW_stack_found} == "y") then
      echo "set movie_stackname_raw = ${importimage_pattern}_${newimagenumber}_stack_raw.${file_ending}" >> ${olddir}/LOGS/${scriptname}.results
    endif
    echo "set imagenumber = ${newimagenumber}" >> ${olddir}/LOGS/${scriptname}.results
    echo "set imagename_original = ${movie_average}/${importimage}" >> ${olddir}/LOGS/${scriptname}.results
    echo "set initialization_reset = y" >> ${olddir}/LOGS/${scriptname}.results
    echo "set initialization_executable = y" >> ${olddir}/LOGS/${scriptname}.results
    set fullpath = `pwd`
    cd ${olddir}
    #
    @ import_imagenumber++
    #
    # This tells the GUI to get back to the original dir for setting parameters
    echo "<IMAGEDIR>" >> ${olddir}/LOGS/${scriptname}.results
    echo "set -force import_imagenumber = ${import_imagenumber}"  >> ${olddir}/LOGS/${scriptname}.results
  else
    ${proc_2dx}/protest "ERROR: ${movie_average}/${importimage} not found."
  endif
  @ irun++
end
#
\rm -f tmp.tmp
#
# This tells the GUI that new images were added and the project library should be updated
echo "<IMPORTDIR>" >> LOGS/${scriptname}.results
#
echo ":: "
echo "::  Image data was imported into ${import_target_dirname}"
echo ":: "
echo "::  Now Refresh the Library in the Project Library view."
echo ":: "
echo "<<@progress: 100>>"
${proc_2dx}/linblock "Normal End."
#
echo "<<@evaluate>>"
#
